package com.alog.common.code;

import java.util.ArrayList;
import java.util.List;

public class SyncQueue {
    private List<String> arr = new ArrayList();
    private static volatile SyncQueue instance ;
    private static Object initLock = new Object();
    private Object optLock = new Object();
    public int count = 0;
    private SyncQueue(){}

    public static SyncQueue getInstance(){
        if(instance == null){
            synchronized (initLock){
                if(instance == null){
                    instance = new SyncQueue();
                }
            }
        }
        return instance;
    }

    public void add() {
        while (true){
            synchronized (optLock){
                if(arr.size() > 0){
                    try {
                        optLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }
                arr.add((++count) + "");
                optLock.notifyAll();
                System.out.println(Thread.currentThread().getName() + " add " + count);
                break;
            }
        }
    }

    public String poll() {
        String content = null;
        while (true){
            synchronized (optLock){
                if(arr.size() <= 0){
                    try {
                        optLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }
                content = arr.remove(0);
                optLock.notifyAll();
                System.out.println(Thread.currentThread().getName() + " poll " + content);
                break;
            }
        }
        return content;
    }

}
